<?php
/**
 * @author: xaboy<365615158@qq.com>
 * @day: 2017/11/11
 */

namespace app\__MODULE__\model;
use think\Model;
use think\facade\Cache;


/**
 * 产品管理 model
 * Class StoreProduct
 * @package app\admin\model\store
 */
class Order extends BaseModel
{

    /**
     * 数据表主键
     * @var string
     */
    protected $pk = 'id';

    /**
     * 模型名称
     * @var string
     */
    protected $name = 'Order';


     protected function setAddTimeAttr()
    {
        return time();
    }

     protected function getAddTimeAttr($value)
    {
        return date('Y-m-d H:i:s',$value);
    }

    protected function setCartIdAttr($value)
    {
        return is_array($value) ? json_encode($value) : $value;
    }

    protected function getCartIdAttr($value)
    {
        return json_decode($value, true);
    }


    // public function  getcartInfoAttr($value,$data){
    //     return  json_decode(OrderCartInfo::where('oid',$data['id'])->value('cart_info'),true);
    // }

    /**
     * 退款凭证图片
     * @param  [type] $value [description]
     * @return [type]        [description]
     */
    public function getRefundReasonWapImgAttr($value){
        return $value ? explode(',',$value) : '';
    }
    /**
     * 关联用户信息
     * @return [type] [description]
     */
    public function user(){
        return $this->belongsTo(User::class,'uid')->bind(['nickname']);
    }

    /**
     * 购物车详情
     * @return [type] [description]
     */
    public function cartDetail(){
        return $this->hasMany(OrderCartInfo::class,'oid')->bind(['cart_info']);
    }

    /**
     * 转化订单状态
     * @param  [type] $value [description]
     * @param  [type] $data  [description]
     * @return [type]        [description]
     */
    public  function getStatusNameAttr($value,$item){
        if($item['paid'] ==0 && $item['is_del'] ==1){
               $item['status_name'] = '<span style="color:red">已取消</span>';
           }elseif($item['paid'] == 0 && $item['status'] == 0) {
                $item['status_name'] = '<span style="color:#ccc">未支付</span>';
            } else if ($item['paid'] == 1 && $item['status'] == 0 && $item['refund_status'] == 0) {
                $item['status_name'] = '未发货';
            } else if ($item['paid'] == 1 && $item['status'] == 1 && $item['refund_status'] == 0) {
                $item['status_name'] = '待收货';
            } else if ($item['paid'] == 1 && $item['status'] == 2 && $item['refund_status'] == 0) {
                $item['status_name'] = '已完成';
            }else if ($item['paid'] == 1 && $item['refund_status'] == 1) {
                $refundReasonTime = date('Y-m-d H:i', $item['refund_reason_time']);
                $refundReasonWapImg = json_decode($item['refund_reason_wap_img'], true);
                $refundReasonWapImg = $refundReasonWapImg ? $refundReasonWapImg : [];
                $img = '';
                if (count($refundReasonWapImg)) {
                    foreach ($refundReasonWapImg as $itemImg) {
                        if (strlen(trim($itemImg)))
                            $img .= '<img style="height:50px;" src="' . $itemImg . '" />';
                    }
                }
                   if (!strlen(trim($img))) $img = '无';
                $item['status_name'] = <<<HTML
<b style="color:#f124c7">申请退款</b><br/>
HTML;
            }else if ($item['paid'] == 1 && $item['refund_status'] == 2) {
                $item['status_name'] = '已退款';
            }else if ($item['paid'] == 1 && $item['refund_status'] == 3) {
                $item['status_name'] = '<span style="color:red">已拒绝退款</span>';
            }else{
                $item['status_name'] = '状态异常';
            }
             
            return $item['status_name'];
            
    }
    /**
     * 检查商品是否可以购买
     * @param  [type]  $uid                 [用户id]
     * @param  [type]  $product_id          [商品id]
     * @param  integer $cart_num            [数量]
     * @param  string  $product_attr_unique [商品属性值]
     */
    public static function checkProductStock($uid, $product_id, $cart_num = 1, $product_attr_unique = '')
    {
        if ($cart_num < 1) $cart_num = 1;
        if (!$product_attr_unique) return self::setErrorInfo('请选择商品属性');
        if (!Goods::isValidProduct($product_id))
            return self::setErrorInfo('该产品已下架或删除');
        if (!GoodsAttr::issetProductUnique($product_id, $product_attr_unique))
            return self::setErrorInfo('请选择有效的产品属性');
        if (Goods::getProductStock($product_id, $product_attr_unique) < $cart_num)
            return self::setErrorInfo('该产品库存不足' . $cart_num);
        return true;
    }


       /**获取某个字段总金额
     * @param $cartInfo
     * @param $key 键名
     * @return int|string
     */
    public static function getOrderSumPrice($cartInfo, $key = 'truePrice')
    {
        $SumPrice = 0;
        foreach ($cartInfo as $cart) {
            $SumPrice = bcadd($SumPrice, bcmul($cart['cart_num'], $cart[$key], 2), 2);
        }
        return $SumPrice;
    }


    /**
     * 缓存订单信息
     * @param $uid
     * @param $cartInfo
     * @param $priceGroup
     * @param array $other
     * @param int $cacheTime
     * @return string
     * @throws \Psr\SimpleCache\InvalidArgumentException
     */
    public static function cacheOrderInfo($uid, $cartInfo, $priceGroup ,$cacheTime = 3600)
    {
        $key = md5(time());
        Cache::set('user_order_' . $uid . $key, compact('cartInfo', 'priceGroup'), $cacheTime);
        return $key;
    }

    /**
     * 获取订单缓存信息
     * @param $uid
     * @param $key
     * @return mixed|null
     * @throws \Psr\SimpleCache\InvalidArgumentException
     */
    public static function getCacheOrderInfo($uid, $key)
    {
        $cacheName = 'user_order_' . $uid . $key;
        if (!Cache::has($cacheName)) return null;
        return Cache::get($cacheName);
    }

    /**
     * 删除订单缓存
     * @param $uid
     * @param $key
     */
    public static function clearCacheOrderInfo($uid, $key)
    {
        Cache::delete('user_order_' . $uid . $key);
    }

    /**
     * 根据优惠券重新计算订单金额
     * @param [int] $uid 用户id
     * @param string $key 商户订单key
     * @param [int] $coupon_id 用户优惠券记录id
     * @return void
     * @author Sam
     * date 2021-09-22
     */
    public  static function computeOrderPrice($uid, $key, $coupon_id){
        if (self::where(['unique' => $key, 'uid' => $uid])->count()) return self::setErrorInfo('订单已经生成', true);
        $userInfo = User::get($uid);
        if (!$userInfo) return self::setErrorInfo('用户不存在!', true);
        $cartGroup = self::getCacheOrderInfo($uid, $key);
        if (!$cartGroup) return self::setErrorInfo('订单已过期,请刷新当前页面!', true);
        $cartInfo = $cartGroup['cartInfo'];
        $priceGroup = $cartGroup['priceGroup'];
        $payPrice = (float)$priceGroup['totalPrice'];
        $couponInfo = StoreCouponUser::where('id', $coupon_id)->where('uid', $uid)->find();
        if (!$couponInfo) return self::setErrorInfo('选择的优惠劵无效!', true);
        $coupons = StoreCouponUser::getUsableCouponList($uid, ['valid' => $cartInfo], $payPrice);
        $flag = false;
        foreach ($coupons as $coupon) {
            if ($coupon['id'] == $coupon_id) {
                $flag = true;
                continue;
            }
        }
        if (!$flag){
            return self::setErrorInfo('不满足优惠劵的使用条件!', true);
        }
        $payPrice = (float)bcsub($payPrice, $couponInfo['coupon_price'], 2);
        $couponPrice = $couponInfo['coupon_price'];
        return [
            'total_price'  => $priceGroup['totalPrice'],
            'pay_price'    => $payPrice <=0 ? 0 : $payPrice,
            'coupon_price' => $couponPrice
        ];
    }
    /**
     * 生成订单
     * @param [int] $uid 用户id
     * @param string $key 订单预生成key
     * @param [int] $addressId 地址ID
     * @param [int] $user_coupon_id 用户优惠券id
     * @param string $mark   订单备注
     * @return void
     * @author Sam
     * date 2021-09-22
     */
    public static function cacheKeyCreateOrder($uid, $key, $addressId, $mark = '',$user_coupon_id='')
    {
        self::beginTrans();
        try {
            if (self::where(['unique' => $key, 'uid' => $uid])->count()) return self::setErrorInfo('请勿重复提交订单', true);
            $userInfo = User::get($uid);
            if (!$userInfo) return self::setErrorInfo('用户不存在!', true);
             $cartGroup = self::getCacheOrderInfo($uid, $key);
            if (!$cartGroup) return self::setErrorInfo('订单已过期,请刷新当前页面!', true);
            $cartInfo = $cartGroup['cartInfo'];
            $priceGroup = $cartGroup['priceGroup'];
            $payPrice = (float)$priceGroup['totalPrice'];
            if (!$addressId) return self::setErrorInfo('请选择收货地址!', true);
            if ((!UserAddress::where(['uid' => $uid, 'id' => $addressId])->count() || !($addressInfo = UserAddress::get($addressId))))
                    return self::setErrorInfo('地址选择有误!', true);
            $cartIds = [];
            $totalNum = 0;
            foreach ($cartInfo as $cart){
                if (!self::checkProductStock($uid, $cart['product_id'], $cart['cart_num'], $cart['product_attr_unique'])) {
                    return false;
                }
                $cartIds[] = $cart['id'];
                $totalNum += $cart['cart_num'];
            }
            if(isset($user_coupon_id) && $user_coupon_id >0){
                $couponInfo = StoreCouponUser::where('id', $user_coupon_id)->where('uid', $uid)->find();
                if (!$couponInfo) return self::setErrorInfo('选择的优惠劵无效!', true);
                $coupons = StoreCouponUser::getUsableCouponList($uid, ['valid' => $cartInfo], $payPrice);
                $flag = false;
                foreach ($coupons as $coupon) {
                    if ($coupon['id'] == $user_coupon_id) {
                        $flag = true;
                        continue;
                    }
                }
                if (!$flag){
                    return self::setErrorInfo('不满足优惠劵的使用条件!', true);
                }
                $user_coupon      =  StoreCouponUser::useCoupon($user_coupon_id);
                if (!$user_coupon) return self::setErrorInfo('使用优惠劵失败!', true);
                $payPrice = (float)bcsub($payPrice, $couponInfo['coupon_price'], 2);
                $couponPrice = $couponInfo['coupon_price'];
            }else{
                $user_coupon_id = 0;
                $couponPrice    = 0;    
            }
            if ($payPrice <= 0) $payPrice = 0;
            $orderInfo = [
                'uid' => $uid,
                'order_id' =>self::getNewOrderId(),
                'real_name' => $addressInfo['real_name'],
                'user_phone' => $addressInfo['phone'],
                'user_address' => $addressInfo['province'] . ' ' . $addressInfo['city'] . ' ' . $addressInfo['district'] . ' ' . $addressInfo['detail'],
                'cart_id' => $cartIds,
                'total_num' => $totalNum,
                'total_price' => $priceGroup['totalPrice'],
                'pay_price' => $payPrice,
                'paid' => 0,
                'mark' => htmlspecialchars($mark),
                'cost' => $priceGroup['costPrice'],
                'add_time' => time(),
                'unique' => $key,
                'coupon_id' => $user_coupon_id,
                'coupon_price' => $couponPrice
            ];
            $order = self::create($orderInfo);
            if (!$order) return self::setErrorInfo('订单生成失败!', true);
            //保存购物车商品信息
            $res =  OrderCartInfo::setCartInfo($order['id'], $cartInfo);
            $res2 = GoodsCart::where('id', 'IN', $cartIds)->update(['is_pay' => 1]); //修改购物车状态
            if (!$res|| !$res2) return self::setErrorInfo('订单生成失败!', true);
            self::clearCacheOrderInfo($uid, $key);
            self::commitTrans();
            StoreOrderStatus::status($order['id'], 'cache_key_create_order', '订单生成');
            return $order;
        } catch (\PDOException $e) {
            self::rollbackTrans();
            return self::setErrorInfo('生成订单时SQL执行错误错误原因：' . $e->getMessage());
        } catch (\Exception $e) {
            self::rollbackTrans();
            return self::setErrorInfo('生成订单时系统错误错误原因：' . $e->getMessage().$e->getLine());
        }
    }

    /**
     * 优惠券
     * @return void
     * @author Sam
     * date 2021-09-22
     */
    public function coupon(){
        return $this->belongsTo('store_coupon_user','coupon_id');
    }

        /**
     * 生成订单唯一id
     * @param $uid 用户uid
     * @return string
     */
    public static function getNewOrderId()
    {
        list($msec, $sec) = explode(' ', microtime());
        $msectime = number_format((floatval($msec) + floatval($sec)) * 1000, 0, '', '');
        $orderId = 'MK' . $msectime . mt_rand(10000, 99999);
        if (self::where(['order_id' => $orderId])->count()) $orderId = 'wx' . $msectime . mt_rand(10000, 99999);
        return $orderId;
    }


       /**
     * 微信支付 为 0元时
     * @param $order_id
     * @param $uid
     * @return bool
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public static function jsPayPrice($order_id, $uid)
    {
        $orderInfo = self::where('uid', $uid)->where('order_id', $order_id)->where('is_del', 0)->find();
        if (!$orderInfo) return self::setErrorInfo('订单不存在!');
        if ($orderInfo['paid']) return self::setErrorInfo('该订单已支付!');
        $userInfo = User::get($uid);
        self::beginTrans();
        $res = self::paySuccess($order_id, 'weixin');//微信支付为0时
        self::checkTrans($res);
        return $res;
    }


        /**
     * //TODO 支付成功后
     * @param $orderId
     * @param $paytype
     * @param $notify
     * @return bool
     */
    public static function paySuccess($orderId, $paytype = 'weixin')
    {
        $order = self::where('order_id', $orderId)->find();
        $resPink = true;
        $res = self::where('order_id', $orderId)->update(['paid' => 1, 'pay_type' => $paytype, 'pay_time' => time()]);//订单改为支付
        //支付成功后
        $cartInfo =  GoodsCart::where('id','in',$order->cart_id)->select();
        foreach ($cartInfo as $cart) {
            //减库存加销量
          $res1 =   Goods::decProductStock($cart['cart_num'], $cart['product_id'], $cart['product_attr_unique']);
        }
         $res2 = false !== GoodsCart::where('id', 'IN', $order->cart_id)->update(['is_pay' => 1]);
         $res = $res1 && $res2;
        return false !== $res;
    }

     /**
     * 个人中心获取个人订单列表和订单搜索
     * @param int $uid 用户uid
     * @param int | string 查找订单类型
     * @param int $first 分页
     * @param int 每页显示多少条
     * @param string $search 订单号
     * @return array
     * */
    public static function getUserOrderSearchList($uid, $type, $page, $limit, $search)
    {
        if ($search) {
            $order = self::searchUserOrder($uid, $search) ?: [];
            $list = $order == false ? [] : [$order];
        } else {
            $list = self::getUserOrderList($uid, $type, $page, $limit);
        }
        foreach ($list as $k => $order) {
            $list[$k] = self::tidyOrder($order, true);
            foreach ($order['cartInfo'] ?: [] as $key => $product) {
                $list[$k]['cartInfo'][$key]['is_reply'] = GoodsComment::where(['uid'=>$uid,'goods_id'=>$product['product_id']])->count() ? true :false;
            }
        }
        return $list;
    }

        /**
     * 获取订单并分页
     * @param $uid
     * @param string $status
     * @param int $page
     * @param int $limit
     * @return mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public static function getUserOrderList($uid, $status = '', $page = 0, $limit = 8)
    {
        if ($page) $list = self::statusByWhere($status)->where('is_del', 0)->where('uid', $uid)
            ->field('add_time,id,order_id,pay_price,total_num,total_price,paid,status,refund_status,pay_type,coupon_price,deduction_price,delivery_type,is_del')
            ->order('add_time DESC')->page((int)$page, (int)$limit)->select()->toArray();
        else  $list = self::statusByWhere($status)->where('is_del', 0)->where('uid', $uid)
            ->field('add_time,id,order_id,pay_price,total_num,total_price,,paid,status,refund_status,pay_type,coupon_price,deduction_price,delivery_type,is_del')
            ->order('add_time DESC')->page((int)$page, (int)$limit)->select()->toArray();
        foreach ($list as $k => $order) {
            $list[$k] = self::tidyOrder($order, true);
        }

        return $list;
    }

    /**
     * 状态查询
     * @param [type] $status 状态查询
     * @param [type] $model  模型
     * @return void
     * @author Sam
     * date 2022-01-22
     */
    public static function statusByWhere($status, $model = null)
    {
        if ($model == null) $model = new self();
        if ('' === $status)
            return $model;
        else if ($status == 0)//未支付
            return $model->where('paid', 0)->where('status', 0)->where('refund_status', 0)->where('is_del', 0);
        else if ($status == 1)//已支付 未发货
            return $model->where('paid', 1)->where('status', 0)->where('refund_status', 0)->where('is_del', 0);
        else if ($status == 2)//已支付  待收货
            return $model->where('paid', 1)->where('status', 1)->where('refund_status', 0)->where('is_del', 0);
        else if ($status == 3)// 已支付  已收货  待评价
            return $model->where('paid', 1)->where('status', 2)->where('refund_status', 0)->where('is_del', 0);
        else if ($status == 4)// 交易完成
            return $model->where('paid', 1)->where('status', 3)->where('refund_status', 0)->where('is_del', 0);
        else if ($status == -1)//退款中
            return $model->where('paid', 1)->where('refund_status', 1)->where('is_del', 0);
        else if ($status == -2)//已退款
            return $model->where('paid', 1)->where('refund_status', 2)->where('is_del', 0);
        else if ($status == -3)//退款
            return $model->where('paid', 1)->where('refund_status', 'in', '1,2')->where('is_del', 0);
        else if ($status == -4)//已删除
            return $model->where('is_del', 1);
        else if ($status == 9)//已卖出
            return $model->where('paid', 1)->where('refund_status', 0)->where('is_del', 0);
        else
            return $model;
    }
    
        /**
     * 获取订单信息
     * @param $id
     * @param string $field
     * @return array|null|\think\Model
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public static function getOrderInfo($id, $field = 'order_id')
    {
        return self::where('id', $id)->field($field)->find();
    }

        /**
     * 搜索某个订单详细信息
     * @param $uid
     * @param $order_id
     * @return bool|mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public static function searchUserOrder($uid, $order_id)
    {
        $order = self::where('uid', $uid)->where('order_id', $order_id)->where('is_del', 0)->field('id,order_id,pay_price,total_num,total_price,pay_postage,total_postage,paid,status,refund_status,pay_type,coupon_price,deduction_price,delivery_type,shipping_type')
            ->order('add_time DESC')->find();
        if (!$order)
            return false;
        else
            return self::tidyOrder($order->toArray(), true);

    }
    /**
     * 支付状态转化文本
     * @param  [type] $value [description]
     * @param  [type] $data  [description]
     * @return [type]        [description]
     */
    public function getStatusTextAttr($value,$data){
        $status = [0=>'未支付',1=>'待发货',2=>'待收货',3=>'已完成',4=>'申请退款',5=>'已退款',6=>'退款拒绝'];
        if($data['paid'] ==0 && $data['status'] ==0 && $data['refund_status'] == 0){
            return $status[0];
        }elseif($data['paid'] ==1 && $data['status'] ==0 && $data['refund_status'] == 0){
            return $status[1];
        }elseif($data['paid'] ==1 && $data['status'] ==1 && $data['refund_status'] == 0){
            return $status[2];
        }elseif($data['paid'] ==1 && $data['status'] ==2 && $data['refund_status'] == 0){
            return $status[3];
        }elseif($data['paid'] ==1 &&  $data['refund_status'] == 1){
            return $status[4];
        }elseif($data['paid'] ==1 &&  $data['refund_status'] == 2){
            return $status[5];
        }elseif($data['paid'] ==1 &&  $data['refund_status'] == 3){
            return $status[6];
        }else{
            return '状态异常';
        }

    }
        /**
     * 设置订单查询状态
     * @param $where
     */
    public static function search_model($where)
    {   
         $model = self::with(['user','cart_detail']);
         if(isset($where['order_sn']) && $where['order_sn'] !=''){;
            $model = $model->where('order_id','like',"%{$where['order_sn']}%");
         }
         if(isset($where['date_search']) && $where['date_search'] !=''){
            $date = explode(' ~ ',$where['date_search']);
            $model = $model->where('add_time','between time',$date);
         }
        if(isset($where['status']) && $where['status']!=''){
            switch ($where['status']) {
                case 0: //未支付
                   $model = $model->where('paid', 0)->where('status', 0)->where('refund_status', 0);
                    break;
                case 1: //待发货
                    $model = $model->where('paid', 1)->where('status', 0)->where('refund_status', 0);
                    break;
                case 2: //待收货
                     $model = $model->where('paid', 1)->where('status', 1)->where('refund_status', 0);
                    break;
                 case 3: //待评价
                     $model = $model->where('paid', 1)->where('status', 2)->where('refund_status', 0);
                    break;
                 case 4: //已完成
                    $model = $model->where('paid', 1)->where('status', 3)->where('refund_status', 0);
                   break;
                 case  -1: //申请退款中
                     $model =$model->where('paid', 1)->where('refund_status', 1);
                    break;   
                 case  -2: //已退款
                   $model = $model->where('paid', 1)->where('refund_status', 2);
                    break;  
                case  -3: //已拒绝退款
                   $model = $model->where('paid', 1)->where('refund_status',3);
                    break;  
                default:
                    # code...
                    break;
            }
        }
        return $model;
    }

        /**
     * 获取订单状态购物车等信息
     * @param $order
     * @param bool $detail 是否获取订单购物车详情
     * @return mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public static function tidyOrder($order, $detail = false, $isPic = false)
    {
        if ($detail == true && isset($order['id'])) {
            $cartInfo = OrderCartInfo::where('oid', $order['id'])->column('cart_info', 'unique') ?: [];
            $info = [];
            foreach ($cartInfo as $k => $cart) {
                $cart = json_decode($cart, true);
                $cart['unique'] = $k;
                array_push($info, $cart);
                unset($cart);
            }
            $order['cartInfo'] = $info;
        }
        $status = [];
        if (!$order['paid']) {
            $status['_type'] = 0;
            $status['_title'] = '未支付';
            $status['_msg'] = '请完成支付再操作!';
            $status['_class'] = 'nobuy';
        } else if ($order['refund_status'] == 1) {
            $status['_type'] = -1;
            $status['_title'] = '申请退款中';
            $status['_msg'] = '商家审核中,请耐心等待';
            $status['_class'] = 'state-sqtk';
        } else if ($order['refund_status'] == 2) {
            $status['_type'] = -2;
            $status['_title'] = '已退款';
            $status['_msg'] = '已为您退款,感谢您的支持';
            $status['_class'] = 'state-sqtk';
        } else if (!$order['status']) {
            $status['_type'] = 1;
            $status['_title'] = '未发货';
            $status['_msg'] = '商家未发货,请耐心等待';
            $status['_class'] = 'state-nfh';
            
        } else if ($order['status'] == 1) {
            $status['_type'] = 2;
            $status['_title'] = '待收货';
            $_time = StoreOrderStatus::getTime($order['id'], 'delivery_goods');
            $status['_msg'] = date('m月d日H时i分', $_time) . '服务商已发货';
            $status['_class'] = 'state-ysh';
        } else if ($order['status'] == 2) {
            $status['_type'] = 3;
            $status['_title'] = '待评价';
            $status['_msg'] = '已收货,快去评价一下吧';
            $status['_class'] = 'state-ypj';
        } else if ($order['status'] == 3) {
            $status['_type'] = 4;
            $status['_title'] = '交易完成';
            $status['_msg'] = '交易完成,感谢您的支持'; 
            $status['_class'] = 'state-ytk';
        }
        if (isset($order['pay_type']))
            $status['_payType'] = isset(self::$payType[$order['pay_type']]) ? self::$payType[$order['pay_type']] : '其他方式';
        if (isset($order['delivery_type']))
            $status['_deliveryType'] = isset(self::$deliveryType[$order['delivery_type']]) ? self::$deliveryType[$order['delivery_type']] : '其他方式';
        $order['_status'] = $status;
        $order['_pay_time'] = isset($order['pay_time']) && $order['pay_time'] != null ? date('Y-m-d H:i:s', $order['pay_time']) : '';
        $order['_add_time'] = isset($order['add_time']) ? (strstr($order['add_time'], '-') === false ? date('Y-m-d H:i:s', $order['add_time']) : $order['add_time']) : '';
        $order['status_pic'] = '';
        return $order;
    }


            /**
     * 获取订单详情
     * @param $uid
     * @param $key
     * @return array|\think\Model|null
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public static function getUserOrderDetail($uid, $key)
    {
        return self::where('order_id|unique', $key)->where('uid', $uid)->where('is_del', 0)->find();
    }

        /**
     * //TODO 用户确认收货
     * @param $uni
     * @param $uid
     */
    public static function takeOrder($uni, $uid)
    {
        $order = self::getUserOrderDetail($uid, $uni);
        if (!$order) return self::setErrorInfo('订单不存在!');
        $order = self::tidyOrder($order);
        if ($order['_status']['_type'] != 2) return self::setErrorInfo('订单状态错误!');
        self::beginTrans();
        if (false !== self::update(['status' => 2], ['id'=>$order['id']]) &&
            false !== StoreOrderStatus::status($order['id'], 'user_take_delivery', '用户已收货')) {
            try {
                StoreCouponIssue::userTakeOrderGiveCoupon($uid,$order['pay_price']);
            } catch (\Exception $e) {
                self::rollbackTrans();
                return self::setErrorInfo($e->getMessage());
            }
            self::commitTrans();
            return true;
        } else {
            self::rollbackTrans();
            return false;
        }
    }
}